/*
 *  Licensed to PECATS under one or more contributor license agreements below:
 *  1. http://www.mozilla.org/MPL/MPL-1.1.html
 *  2. http://www.gnu.org/licenses/gpl-2.0.html
 *  3. http://www.gnu.org/licenses/lgpl-2.1.html
*/

/* **********************************************************
*  Servlet for Handling Upload of a File
*  Name: FileManagerServlet.java
*  Author: www.pecats.com
*  Date: Sep 15, 2008
************************************************************/

package com.pecats.server.core;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletConfig;
import java.io.IOException;
import java.io.File;
import java.util.List;
import java.util.Iterator;

import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import com.pecats.server.data.ConfigData;

/**
 * Servlet used to upload a file (log file) from a customer to the disk (folder raw-logs)
 */

public class FileManagerServlet extends HttpServlet 
{

    /*
     * Method used to handle incoming http request. It is forwared to doGet method.
     * @param request HttpServletRequest object from the incoming request
     * @param response HttpServletResponse object which forms the response
     * @exception ServletException
     * @exception IOException
    */
    protected void doPost(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException 
	{
		doGet(request,response);

	}

    /*
     * Method used to handle incoming http request.
     * @param request HttpServletRequest object from the incoming request
     * @param response HttpServletResponse object which forms the response
     * @exception ServletException
     * @exception IOException
    */
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException 
	{

		// Get the session
   		HttpSession session = request.getSession();
		String userName = (String) session.getAttribute("Email");
		if (userName == null) 
		{
			request.setAttribute("loginmessage", "The Session has ended, Please login again and then upload file" );
			request.getRequestDispatcher("/LoginJSP.jsp").forward(request, response);
		}
		else
		{
			try
			{

				// Check that we have a file upload request
				boolean isMultipart = ServletFileUpload.isMultipartContent(request);

				// Create a factory for disk-based file items
				FileItemFactory factory = new DiskFileItemFactory();

				// Create a new file upload handler
				ServletFileUpload upload = new ServletFileUpload(factory);

				// Set Max Size of File (Current Max Size 10MB)
//				upload.setSizeMax(Integer.parseInt(ConfigData.maxFileSize));		
	
				// Parse the request
				List /* FileItem */ items = upload.parseRequest(request);
	
				// now iterate over this list
				Iterator itr = items.iterator();
				String path = null;	
				while(itr.hasNext())
				{
	
					FileItem item = (FileItem) itr.next();
		
					// check if the current item is a form field or an uploaded file
					if(item.isFormField())
					{
			
						// get the name of the field
						String fieldName = item.getFieldName();
			
						// if it is name, we can set it in request to thank the user
						if(fieldName.equals("name"))
						request.setAttribute("message", "Thank You: " + item.getString());
				
					}
					 else
					 {
						if (item.getSize()>0)
						{
							// the item must be an uploaded file
							// save it to disk			
							File fullFile = new File(item.getName());		
							path = getServletContext().getRealPath("/") + ConfigData.rawlogsdir + ConfigData.pathseperator + userName;
							File pathFile = new File(path);
							if (pathFile.isDirectory()==false)
							{
								boolean success = (pathFile).mkdir();	
							}
							System.out.println(path);
							File savedFile = new File(path, fullFile.getName());
							item.write(savedFile);
						}
					}
				}
			
				// finally send to the message page
				request.setAttribute("loginmessage", path);
				request.getRequestDispatcher("/BrowseJSP.jsp").forward(request, response);
			}
			catch (Exception ex) 
			{
            		throw new ServletException(ex);
        		}
            } 	
	}
}

